<template>
  <div class="roleList">
      <!-- 面包屑 -->
     <el-breadcrumb separator-class="el-icon-arrow-right">
       <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
       <el-breadcrumb-item>权限管理</el-breadcrumb-item>
       <el-breadcrumb-item>角色列表</el-breadcrumb-item>
     </el-breadcrumb>
     <!-- 添加 -->
      <el-button @click="showDialog" class="addBtn" type="success" plain>添加角色</el-button>
      <!-- 表格 -->
     <el-table
        :data="tableData"
        style="width: 100%">
        <el-table-column  type="expand">
          <template v-slot:default='{row}'>
            <p v-show="row.children.length===0?true:false" style="color:#cccccc;text-align: center">暂无权限</p>
             <!-- 一级权限 -->
              <el-row v-for="l1 in row.children" :key="l1.id" class="l1">
                 <el-col :span="4" >
                   <el-tag closable @close='closeRole(row,l1.id)'>{{l1.authName}}</el-tag>
                   <i class="el-icon-arrow-right"></i>
                 </el-col>
                 <el-col :span="20">
                     <!-- 二级权限 -->
                     <el-row v-for="l2 in l1.children" :key="l2.id" class="l2">
                        <el-col :span="4">
                           <el-tag type="success" closable @close='closeRole(row,l2.id)'>{{l2.authName}}</el-tag>
                           <i class="el-icon-arrow-right"></i>
                        </el-col>
                        <el-col :span="20">
                            <!-- 三级权限 -->
                            <el-tag
                            type="warning"
                            closable
                            v-for="l3 in l2.children"
                            :key="l3.id"
                            class="l3"
                             @close='closeRole(row,l3.id)'>
                              {{l3.authName}}
                            </el-tag>
                        </el-col>
                     </el-row>
                 </el-col>
              </el-row>
          </template>
        </el-table-column>
         <el-table-column
          label="#"
          type="index">
        </el-table-column>
        <el-table-column
          label="角色名称"
          prop="roleName">
        </el-table-column>
        <el-table-column
          label="描述"
          prop="roleDesc">
        </el-table-column>
        <el-table-column
          label="操作">
          <template v-slot:default='obj'>
            <el-button @click="showModDialog(obj.row)" plain size="small" type="primary" icon="el-icon-edit" ></el-button>
            <el-button @click="delRole(obj.row.id)" plain size="small" type="danger"  icon="el-icon-delete"></el-button>
            <el-button @click="allotRole(obj.row)" plain size="small" type="success" icon="el-icon-check">分配角色</el-button>
          </template>
        </el-table-column>
     </el-table>

     <!-- 添加对话框 -->
      <el-dialog title="添加角色" :visible.sync="showAddRole" @close='addClose'  width="40%">
        <el-form :model="form" :rules="rules" ref="form">
          <el-form-item label="角色名称" prop="roleName" :label-width="formLabelWidth">
            <el-input v-model="form.roleName" placeholder="请输入角色名称"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc" :label-width="formLabelWidth">
           <el-input v-model="form.roleDesc" placeholder="请输入角色描述"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="showAddRole = false">取 消</el-button>
          <el-button type="primary" @click="addRole" >确 定</el-button>
        </div>
      </el-dialog>

     <!-- 修改角色对话框 -->
      <el-dialog title="修改角色" :visible.sync="showModRole"  width="40%">
        <el-form :model="modForm" :rules="rules" ref="modForm">
          <el-form-item label="角色名称" prop="roleName" :label-width="formLabelWidth">
            <el-input v-model="modForm.roleName" placeholder="请输入角色名称"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc" :label-width="formLabelWidth">
           <el-input v-model="modForm.roleDesc" placeholder="请输入角色描述"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="showModRole = false">取 消</el-button>
          <el-button type="primary" @click="modRole" >确 定</el-button>
        </div>
      </el-dialog>

      <!-- 分配角色 -->
      <el-dialog title="分配角色" :visible.sync="showAllotRole"  width="40%">
          <el-tree
            :data="data"
            default-expand-all
            node-key="id"
            ref="tree"
            show-checkbox
            :props="defaultProps"
          >
          </el-tree>
          <div slot="footer" class="dialog-footer">
                <el-button @click="showAllotRole = false">取 消</el-button>
                <el-button @click='setAllotRole' type="primary" >确 定</el-button>
          </div>
      </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 所有角色
      tableData: [],
      // 添加角色
      showAddRole: false,
      form: {
        roleName: '',
        roleDesc: ''
      },
      // 修改角色
      showModRole: false,
      modForm: {
        id: '',
        roleName: '',
        roleDesc: ''
      },
      formLabelWidth: '120px',
      // 分配角色
      showAllotRole: false,
      // 分配角色
      data: [],
      // 角色 id
      roleid: '',
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      // 校验
      rules: {
        roleName: [
          { required: true, message: '角色名不能为空', trigger: ['change', 'blur '] }
        ],
        roleDesc: [
          { required: true, message: '角色描述不能为空', trigger: ['change', 'blur '] }
        ]
      }
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    async getRoleList () {
      try {
        const { data, meta } = await this.$axios.get('roles')
        // console.log(data)

        if (meta.status === 200) {
          this.tableData = data
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 显示添加角色对话框
    showDialog () {
      this.showAddRole = true
    },
    // 每当添加对话框关闭时重置 form 表单的数据
    addClose () {
      this.$refs.form.resetFields()
    },
    // 添加角色
    async addRole () {
      try {
        await this.$refs.form.validate()
        // 当执行到这一步说明 校验一斤成功  发送 ajax
        const { meta } = await this.$axios.post('roles', this.form)
        if (meta.status === 201) {
          this.$message({
            message: meta.msg,
            type: 'success',
            duration: 1000
          })
          // 关闭 对话框
          this.showAddRole = false
          // 重新渲染
          this.getRoleList()
        } else {
          this.$message({
            message: meta.msg,
            type: 'warning',
            duration: 1000
          })
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 删除角色指定权限
    async closeRole (row, rightId) {
      // 发送 ajax
      const { data, meta } = await this.$axios.delete(`roles/${row.id}/rights/${rightId}`)
      if (meta.status === 200) {
        this.$message({
          message: meta.msg,
          type: 'success',
          duration: 1000
        })

        row.children = data
      } else {
        this.$message({
          message: meta.msg,
          type: 'error',
          duration: 1000
        })
      }
    },
    // 显示修改角色对话框
    showModDialog (row) {
      this.showModRole = true
      this.modForm.roleName = row.roleName
      this.modForm.id = row.id
      this.modForm.roleDesc = row.roleDesc
    },
    // 修改角色
    async modRole () {
      try {
        await this.$refs.modForm.validate()
        // 当执行到这一步说明 校验一斤成功  发送 ajax
        const { id, roleName, roleDesc } = this.modForm
        const { meta } = await this.$axios.put(`roles/${id}`, { roleName, roleDesc })
        if (meta.status === 200) {
          this.$message({
            message: meta.msg,
            type: 'success',
            duration: 1000
          })
          // 关闭 对话框
          this.showModRole = false
          // 重新渲染
          this.getRoleList()
        } else {
          this.$message({
            message: meta.msg,
            type: 'warning',
            duration: 1000
          })
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 删除数据
    async delRole (id) {
      try {
        await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        // 当执行到这里说明 已经点击来确认按钮 发送 ajxa 删除数据
        const { meta } = await this.$axios.delete(`roles/${id}`)
        if (meta.status === 200) {
          this.$message({
            message: meta.msg,
            type: 'success',
            duration: 1000
          })
          // 重新渲染
          this.getRoleList()
        } else {
          this.$message({
            message: meta.msg,
            type: 'warning',
            duration: 1000
          })
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 分配角色
    async allotRole (row) {
      // console.log(row)

      this.showAllotRole = true
      this.roleid = row.id
      //  获取所有的角色权限
      const { data, meta } = await this.$axios.get('rights/tree')
      if (meta.status === 200) {
        // console.log(row.children)
        this.data = data
        // 获取当前角色的权限 id 直接 或去 第三级 权限 的 id 即可
        const authArr = []
        row.children.forEach(l1 => {
          l1.children.forEach(l2 => {
            l2.children.forEach(l3 => {
              authArr.push(l3.id)
            })
          })
        })
        this.$refs.tree.setCheckedKeys(authArr)
      } else {
        console.log(meta.msg)
      }
    },
    // 设置分配角色
    async setAllotRole () {
      // 获取被选中的权限 id
      // this.$refs.tree.getCheckedKeys()  目前被选中的节点的 key 所组成的数组
      //  this.$refs.tree.getHalfCheckedKeys()  返回目前半选中的节点的 key 所组成的数组
      const pair = this.$refs.tree.getCheckedKeys()
      const half = this.$refs.tree.getHalfCheckedKeys()
      const rids = [...pair, ...half].join(',')
      // console.log(rids)

      // 发送 ajax
      const { meta } = await this.$axios.post(`roles/${this.roleid}/rights`, { rids })
      if (meta.status === 200) {
        this.$message({
          message: meta.msg,
          type: 'success',
          duration: 1000
        })
        // 关闭 对话框
        this.showAllotRole = false
        // 重新渲染
        this.getRoleList()
      } else {
        this.$message({
          message: meta.msg,
          type: 'error',
          duration: 1000
        })
      }
    }

  }

}
</script >

<style lang='scss' scoped>
   .roleList{
      .el-breadcrumb{
         height: 40px;
         line-height: 40px;
         border-bottom: 1px solid #cccccc;

      }
      .addBtn{
        margin: 10px 0;
      }
      .l1{
        margin-bottom: 10px;
        border-bottom: 1px dotted #cccccc;
        .l2{
          margin-bottom: 5px;
          .l3{
             margin: 0 5px 10px 0;
          }
        }
      }
   }
</style>
